<template>
	<view class="" @click="show = false">
		<view class="container">
			<image :src="searchBgImg" mode="aspectFill" class="bg"></image>
			<view class="index-nav u-flex u-col-center u-row-center">
				<view class="item" :class="{on:type==item.type}" v-for="(item,index) in navlist" :key="index"
					@click="change(item)">
					{{item.name}}
				</view>
			</view>
			<view class="index-search">
				<view class="search">
					<view class="l">
						<uni-icons type="search" size="20" color="#D1D1D6"> </uni-icons>
					</view>
					<view class="c">
						<input class="uni-input" v-model="kw" confirm-type="search" placeholder="请输入你要查询的物品名称"
							placeholder-style="color:#D1D1D6;font-size: 28rpx;" @input="handleInput"
							@confirm="confirm" />
					</view>
					<view class="r" @click="confirm">
						查询
					</view>
				</view>
				<view class="searchbtns" v-if="verifyUp == 0">
					<image class="img" src="/static/rm.png" mode=""></image>
					<view class="btns">
						<view class="itmes" v-for="(item,index) in searchList" :key="index"
						@click="toSearch(item.dictLabel)">
							{{item.dictLabel}}
						</view>
					</view>
				</view>
				<view class="s-list" v-if="show">
					<view class="item u-flex u-col-center u-row-between" v-for="(item,index) in list" :key="index"
						@click="toSearch(item.name)">
						<view class="l">
							<uni-icons type="search" size="20" color="#D1D1D6"> </uni-icons>
						</view>
						<view class="c u-l-1">
							<rich-text :nodes="item.name2"></rich-text>
						</view>
						<view class="r">
							<image src="@/static/index1.png" mode="aspectFill"></image>
						</view>
					</view>
				</view>
			</view>
	
			<view class="textss">
				<view class="">
					本小程序仅提供价格查询服务
				</view>
				<view class="">
					不提供交易售卖功能
				</view>
			</view>
		</view>

		<uni-popup ref="popup" type="center">
			<view class="m-pop">
				<uni-icons type="closeempty" size="22" color="#AEAEAE" class="icons" @click="close"></uni-icons>
				<image src="@/static/ad1.png" mode="aspectFill"></image>
				<view class="tips">
					当前每日免广告查询次数为1次 <br> 本次查询需看完整广告
				</view>
				<view class="btns u-flex u-col-center u-row-between">
					<view class="btn btn1" @click="close">
						暂不
					</view>
					<view class="btn btn2" @click="handleok">
						确认
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		login,
		messageSeecount,
		webconfig,
		inputSearch,
		getdict
	} from '@/common/http.api.js';
	export default {
		data() {
			return {
				navlist: [{
						name: '收货报价',
						type: 2,
						searchType:'hot_word_buy'
					},
					{
						name: '现货报价',
						type: 1,
						searchType:'hot_word_sell'
					}
				],
				searchBgImg: '',
				dysearch: '',


				show: false,
				kw: '',
				type: 2,
				list: [],
				name: '',

				ad: null,
				verifyUp:0,
				
				
				
				
				searchList:[]

			}
		},
		onLoad() {
			
		},
		onUnload() {
			if (this.ad) {
				this.ad.offClose(this.onCloseListener);
				this.ad.destroy()
			}
		},
		onShow() {
			if (uni.getStorageSync('userToken')) {
				this.getSeeCount()
				this.getwebconfig()
				if (this.type == 2) {
					this.getddd('hot_word_buy')
				}else{
					this.getddd('hot_word_sell')
				}
			} else {
				this.handleLogin()
			}
		},
		methods: {
			getddd(type){
				getdict(type).then(res=>{
					if(res.code == 200){
						this.searchList = res.data
					}
				})
			},
			change(item) {
				this.getddd(item.searchType)
				if (this.type != item.type) {
					this.type = item.type
					this.kw = ''
					this.list = []
					this.name = ''
					this.show = false
				}
			},
			confirm() {
				// if (!this.kw) {
				// 	uni.showToast({
				// 		title: '请输入搜索内容',
				// 		icon: "none"
				// 	});
				// 	return
				// }
				this.toSearch(this.kw)
			},

			handleInput() {
				this.list = []
				this.show = true
				if (!this.kw) {
					return
				}
				inputSearch({
					name: this.kw,
					type: this.type
				}).then(res => {
					if (res.code == 200) {
						let list = res.data
						if (list.length > 0) {
							this.list = list.map(item => {
								let name2 = ''
								if (item.includes(this.kw)) {
									const wrappedStr = item.replace(new RegExp(this.kw, 'g'),
										`<span style="color:#FF6F07">${this.kw}</span>`);
									name2 = wrappedStr
								} else {
									name2 = item
								}
								return {
									name: item,
									name2: name2
								}
							})
							this.show = true
						} else {
							this.list = []
							this.show = false
						}
					}
				})
			},
			toSearch(name) {
				this.name = name
				const dateObj = new Date();
				const year = dateObj.getFullYear(); // 获取当前年份
				const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取当前月份，其中需要将月份加1，因为月份是从0开始计数的
				const day = ("0" + dateObj.getDate()).slice(-2); // 获取当前日期
				const formattedDate = `${year}-${month}-${day}`; // 格式化日期
				// #ifdef MP-TOUTIAO
				// #endif
				if (this.dysearch == 0) {
					//开启未开启搜索付费
					this.show = false
					this.list = []
					this.setPageRandom()
					uni.navigateTo({
						url: `/pages/index/searchList?name=${this.name}&type=${this.type}`
					})
				} else {
					//开启搜索付费
					if (uni.getStorageSync('userSearchData')) {
						let userSearchData = uni.getStorageSync('userSearchData')
						if (formattedDate == userSearchData.date && uni.getStorageSync('uid') == userSearchData.uid) {
							//看过
							this.$refs.popup.open()
						} else {
							this.addTimes(formattedDate)
						}
					} else {
						this.addTimes(formattedDate)
					}
				}
			},
			addTimes(formattedDate) {
				uni.setStorageSync('userSearchData', {
					date: formattedDate,
					uid: uni.getStorageSync('uid')
				})
				this.show = false
				this.list = []
				this.setPageRandom()
				uni.navigateTo({
					url: `/pages/index/searchList?name=${this.name}&type=${this.type}`
				})
			},
			setPageRandom() {
				this.kw = ''

				function generateRandomString(length) {
					const chars = '0123456789abcdefghijklmnopqrstuvwxyz'; // 包含的字符
					let result = '';
					for (let i = 0; i < length; i++) {
						const randomIndex = Math.floor(Math.random() * chars.length); // 随机索引
						result += chars[randomIndex];
					}
					return result;
				}
				uni.setStorageSync('sListPageRandom', generateRandomString(10))
			},
			close() {
				this.$refs.popup.close()
			},
			handleok() {
				this.close()
				uni.showLoading({
					title: '加载中...'
				})
				// #ifdef MP-TOUTIAO
				// 先销毁已存在的广告实例，避免重复绑定
				if (this.ad) {
					this.ad.offClose() // 移除之前的关闭事件监听
					this.ad.destroy() // 销毁实例
				}
				// 创建新的广告实例
				this.ad = tt.createRewardedVideoAd({
					adUnitId: "qnyjogx75a7vfoogil",
				});

				// 监听错误
				this.ad.onError((err) => {
					tt.hideLoading();
					uni.hideLoading();
					uni.showToast({
						title: `广告错误: ${err.errCode}`,
						icon: "none"
					});
				});

				// 定义关闭事件处理函数
				const closeHandler = (data) => {
					// 先移除事件监听，避免重复执行
					this.ad.offClose(closeHandler);

					uni.hideLoading();
					if (data.isEnded) {
						this.$modal.msg('观看完成')
						this.setPageRandom()
						console.log('观看完成');
						setTimeout(() => {
							uni.navigateTo({
								url: `/pages/index/searchList?name=${this.name}&type=${this.type}`
							})
						}, 500)
					} else {
						this.$modal.msg('未观看完视频')
					}
					// 完成后销毁实例
					this.ad.destroy();
					this.ad = null;
				};

				// 绑定关闭事件
				this.ad.onClose(closeHandler);

				// 加载并显示广告
				this.ad.load()
					.then(() => {
						this.ad.show()
							.catch(err => {
								console.error('广告显示失败', err);
								uni.hideLoading();
								this.$modal.msg('广告加载失败，请重试')
							})
					})
					.catch(err => {
						console.error('广告加载失败', err);
						uni.hideLoading();
						this.$modal.msg('广告加载失败，请重试')
					})
				// #endif
			},
			getwebconfig() {
				webconfig({}).then(res => {
					if (res.code == 200) {
						this.dysearch = res.data.dysearch
						this.searchBgImg = res.data.searchBgImg
						this.verifyUp = res.data.verifyUp
					}
				})
			},
			getSeeCount() {
				messageSeecount({}).then(res => {
					if (res.code == 200) {
						let num = res.data
						if (num > 0) {
							uni.setTabBarBadge({
								index: 1,
								text: '新'
							})
						} else {
							uni.removeTabBarBadge({
								index: 1
							})
						}
					}
				})
			},
			handleLogin() {
				tt.login({
					force: true,
					success: (r) => {
						login({
							code: r.code
						}).then(res => {
							if (res.code == 200) {
								uni.setStorageSync('openId', res.data.openId)
								uni.setStorageSync('userToken', res.data.token)
								uni.setStorageSync('loginTime', new Date().getTime())
								this.getSeeCount()
								this.getwebconfig()
								this.getddd('hot_word_buy')
							}
						})
					},
					fail(res) {
						console.log(`login 调用失败`);
					},
				});
			},
		}
	}
</script>

<style lang="scss">
	$color: #FF6F07;
	.textss{
		width: 750rpx;
		color: red;
		font-size: 24rpx;
		text-align: center;
		color:#FF6F07;
		position: fixed;
		bottom: 20rpx;
		z-index: 99;
	}
	.m-pop {
		width: 620rpx;
		height: 560rpx;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		flex-direction: column;
		box-sizing: border-box;
		padding: 20rpx 40rpx 20rpx;
		border-radius: 20rpx;
		background: #fff;
		z-index: 99999;

		.icons {
			position: absolute;
			right: 30rpx;
			top: 30rpx;
		}

		image {
			width: 192rpx;
			height: 192rpx;
		}

		.tips {
			margin-top: 40rpx;
			line-height: 40rpx;
			font-size: 32rpx;
			color: #000000;
			text-align: center;

		}

		.btns {
			width: 100%;
			margin-top: 60rpx;

			.btn {
				text-align: center;
				font-size: 32rpx;
				width: calc(50% - 10rpx);
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 20rpx;
			}

			.btn1 {

				background: #F9F9F9;
				color: #D1CDCD;
			}

			.btn2 {
				color: #fff;
				background: linear-gradient(270deg, #FF6F07 0%, #FFA666 100%);

			}
		}
	}

	.container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		position: relative;
		padding-top: 160rpx;

		.bg {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			width: 100%;
			height: 100%;
			z-index: 1;

			// filter: blur(5rpx);
			&::after {
				content: "";
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				width: 100%;
				height: 100%;
				background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, .4) 20%, rgba(255, 255, 255, 1) 50%, rgba(255, 255, 255, .4) 80%, rgba(255, 255, 255, 0) 100%);
				pointer-events: none;
				/* 确保渐变层不会影响图片的点击 */
			}
		}
	}

	.index-nav {
		width: calc(100% - 200rpx);
		margin: 0rpx auto 60rpx;
		position: relative;
		z-index: 2;

		.item {
			flex: 1;
			text-align: center;
			height: 70rpx;
			line-height: 70rpx;
			font-size: 36rpx;
			color: #666;
		}

		.on {
			font-weight: bold;
			font-size: 48rpx;
			color: #11192D;
			position: relative;

			&::after {
				content: '';
				position: absolute;
				bottom: -20rpx;
				width: 48rpx;
				height: 8rpx;
				background: $color;
				border-radius: 4rpx;
				left: 50%;
				margin-left: -24rpx;

			}
		}
	}

	.index-search {
		width: calc(100% - 80rpx);
		margin: 0 auto;
		position: relative;
		z-index: 2;
		border-radius: 12rpx;

		.search {
			width: 100%;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;
			padding: 0 10rpx 0 0;
		background-color: #fff;

			.l {
				width: 80rpx;
				height: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				text-align: center;
				position: relative;

				&::after {
					content: '';
					position: absolute;
					top: 0;
					right: 0;
					bottom: 0;
					width: 2rpx;
					background-color: #eee;
				}

				image {
					width: 40rpx;
					height: 40rpx;
				}

			}

			.c {
				flex: 1;
				width: 1rpx;
				margin-left: 20rpx;
				height: 60rpx;
				line-height: 60rpx;
				margin-right: 20rpx;

				input {
					width: 100%;
					height: 60rpx;
					line-height: 60rpx;
					font-size: 28rpx;
					color: #11192D;
				}

			}

			.r {
				width: 140rpx;
				height: 80rpx;
				line-height: 80rpx;
				color: #fff;
				font-size: 30rpx;
				text-align: center;
				background: linear-gradient(270deg, #FF6F07 0%, #FFA666 100%);
				border-radius: 16rpx;
			}
		}
		.searchbtns{
			.img{
				width: 148rpx;
				height: 36rpx;
				margin-top: 34rpx;
			}
			.btns{
				display: flex;
				flex-wrap: wrap;
				margin-top: 24rpx;
				.itmes{
					height: 60rpx;
					background: #F2F2F2;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					padding: 0rpx 15rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #777777;
					line-height: 60rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
				}
			}
		}

		.s-list {
			padding: 0 20rpx;
			position: absolute;
			left: 0;
			right: 0;
			top: 96rpx;
			background-color: #fff;
			z-index: 999;
			border-radius: 0 0 20rpx 20rpx;

			.item {
				border-bottom: 2rpx solid #eee;
				height: 100rpx;
				line-height: 100rpx;

				&:last-child {
					border-bottom: none;
				}


				.l {
					width: 40rpx;
					height: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					text-align: center;

				}

				.c {
					flex: 1;
					width: 1rpx;
					padding: 0 20rpx;
					font-size: 28rpx;
					color: #11192D;

					text {
						color: $color;
					}
				}

				.r {
					width: 40rpx;
					height: 40rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					text-align: center;

					image {
						width: 100%;
						height: 100%;
						display: block;
					}
				}
			}
		}
	}
</style>